package com.commerceE.util;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;

import com.commerceE.common.exception.ServiceException;
import com.commerceE.service.ProductService;


/**
 * Provide relative services for spring.
 *
 */
public class SpringUtil {

	private static ApplicationContext ctx = null;
	
	
	/**
	 * Initiate the spring context.
	 */
	private static void init(){
		if(ctx==null){
			ctx = new ClassPathXmlApplicationContext(
					new String[] { "classpath*:spring/**/applicationContext*.xml" });
		}
	}
	
	/**
	 * Get a bean through beanId manually. 
	 * 
	 * @param id
	 * @return
	 */
	public static Object getBeanById(String beanId){
		if(StringUtils.isBlank(beanId)){
			return null;
		}
//		WebApplicationContext webApplCtx = ContextLoader.getCurrentWebApplicationContext();
//		if (webApplCtx != null)
//			return webApplCtx.getBean(beanId);
		
		if(ctx==null){
			init();
		}
		return ctx.getBean(beanId);
	}
	
	public static void main(String[] args) throws ServiceException{
		ProductService productService = (ProductService)getBeanById("productService");
		System.out.println(productService.getAllListOfProduct().size());
	}
	
}
